#!/bin/bash

# 重启Spring Boot应用脚本
# 作者: AI Assistant
# 日期: $(date +%Y-%m-%d)

echo "=========================================="
echo "Spring Boot 应用重启脚本"
echo "=========================================="

# 设置变量
PROJECT_DIR="/Users/shafei/Desktop/AI/demo22"
MAVEN_PATH="/Users/shafei/Desktop/bgyfw-tcpt/maven/apache-maven-3.6.1-tcpt/bin/mvn"
PORT="8081"
APP_NAME="warp-knitting-monitor"

echo "项目目录: $PROJECT_DIR"
echo "Maven路径: $MAVEN_PATH"
echo "应用端口: $PORT"
echo ""

# 切换到项目目录
cd "$PROJECT_DIR" || {
    echo "❌ 错误: 无法切换到项目目录 $PROJECT_DIR"
    exit 1
}

echo "📁 已切换到项目目录: $(pwd)"
echo ""

# 停止现有进程
echo "🛑 正在停止现有进程..."

# 方法1: 通过端口查找并杀死进程
PORT_PID=$(lsof -ti:$PORT 2>/dev/null)
if [ -n "$PORT_PID" ]; then
    echo "   发现端口 $PORT 上的进程 PID: $PORT_PID"
    kill -9 $PORT_PID 2>/dev/null
    echo "   ✅ 已杀死端口 $PORT 上的进程"
else
    echo "   ℹ️  端口 $PORT 上没有发现进程"
fi

# 方法2: 通过进程名查找并杀死进程
SPRING_PID=$(ps aux | grep "spring-boot:run" | grep -v grep | awk '{print $2}')
if [ -n "$SPRING_PID" ]; then
    echo "   发现Spring Boot进程 PID: $SPRING_PID"
    kill -9 $SPRING_PID 2>/dev/null
    echo "   ✅ 已杀死Spring Boot进程"
else
    echo "   ℹ️  没有发现Spring Boot进程"
fi

# 等待进程完全停止
echo "⏳ 等待进程完全停止..."
sleep 3

# 检查端口是否已释放
if lsof -i:$PORT >/dev/null 2>&1; then
    echo "❌ 警告: 端口 $PORT 仍被占用，尝试强制释放..."
    lsof -ti:$PORT | xargs kill -9 2>/dev/null
    sleep 2
fi

echo "✅ 进程停止完成"
echo ""

# 启动新进程
echo "🚀 正在启动新进程..."

# 检查Maven是否存在
if [ ! -f "$MAVEN_PATH" ]; then
    echo "❌ 错误: Maven路径不存在: $MAVEN_PATH"
    exit 1
fi

# 启动应用
echo "   使用Maven启动Spring Boot应用..."
nohup "$MAVEN_PATH" spring-boot:run > app.log 2>&1 &
MAVEN_PID=$!

echo "   Maven进程PID: $MAVEN_PID"
echo "   日志文件: app.log"
echo ""

# 等待应用启动
echo "⏳ 等待应用启动..."
for i in {1..30}; do
    if curl -s http://localhost:$PORT/api/monitor/machines >/dev/null 2>&1; then
        echo "✅ 应用启动成功!"
        echo ""
        
        # 显示应用信息
        echo "📊 应用状态信息:"
        echo "   URL: http://localhost:$PORT"
        echo "   机器API: http://localhost:$PORT/api/monitor/machines"
        echo "   计划API: http://localhost:$PORT/api/monitor/pending-plans"
        echo ""
        
        # 测试API
        echo "🧪 测试API响应:"
        MACHINE_COUNT=$(curl -s http://localhost:$PORT/api/monitor/machines | jq length 2>/dev/null || echo "未知")
        echo "   机器数量: $MACHINE_COUNT"
        
        PLAN_COUNT=$(curl -s http://localhost:$PORT/api/monitor/pending-plans | jq length 2>/dev/null || echo "未知")
        echo "   计划数量: $PLAN_COUNT"
        echo ""
        
        echo "🎉 重启完成! 应用正在运行中..."
        exit 0
    fi
    
    echo "   等待中... ($i/30)"
    sleep 2
done

echo "❌ 错误: 应用启动超时"
echo "请检查日志文件: app.log"
exit 1 